import $ from '../jquery/jquery.min.js';
import ajax from '../utils/ajax'

const searchObj = {
    value: '',
    currentPage: 1,
    pageSize: 5,
    pages: 0,
    total: 0
}


showAdvertiseData();
showPageData();


//打开广告位租赁合同
$('#advertisingLeasing').on('click', '.show-advertise-modal', function () {
    $('#add-advertising-contract-modalbox').show();
    if ($(this).text() == '编辑') {
        //获取选择要修改用户的数据渲染到模态框
        const _id = $(this).data('id');
        $('#advertise-title-p').addClass('gai');
        $('#advertise-title-p').attr('data-id', _id);
        getAdvertiseDatasById(_id);
    } else {
        $('#advertise-title-p').removeClass('gai');
        showCommunityAdvertise();
    }
});



//关闭租赁合同
$('#advertising-return-btn').click(function () {
    $('#add-advertising-contract-modalbox').hide();
    clearData();
});



// size:String,//广告位大小
// price:String,//广告位金额
// locations:String,//广告位位置
// leasee:String,//出租人,租赁方
// leaseeContacts:String,//联系人
// leaseeTel:String,//联系电话

//新增合同||||||||修改合同
$('#advertising-save-contract-btn').click(function () {
    //获取当前输入框的值
    const communityId = $('#advertising-choose-plot').val();
    const advertiseportId = $('#advertiseNumber-select').val();
    const size = $('#advertise-size').val();
    const price = $('#advertise-price').val();
    const locations = $('#advertise-locations').val();
    const leasee = $('#advertise-leasee').val();
    const leaseeContacts = $('#advertise-leaseeContacts').val();
    const leaseeTel = $('#advertise-leaseeTel').val();
    const contractNumber = $('#advertise-contractNumber').val();
    const tenant = $('#advertise-tenant').val();
    const signingDate = $('#advertise-signingDate').val();
    const representative = $('#advertise-representative').val();
    const tenantContacts = $('#advertise-tenantContacts').val();
    const contractType = $('#advertise-contractType').val();
    const term = $('#advertise-term').val();
    const off_hire = $('#advertise-off_hire').val();
    const start_date = $('#advertise-start_date').val();
    const area = $('#advertise-area').val();
    const earnestMoney = $('#advertise-earnestMoney').val();
    const agencyfee = $('#advertise-agencyfee').val();
    const isRentMoney = $('#advertise-isRentMoney').prop('checked');
    const totalMoney = $('#advertise-isRentMoney').prop('checked') ? $('#advertise-totalMoney').val() : 0;
    const increase = $('#advertise-increase').val();
    const earnestExplain = $('#advertise-earnestExplain').val();
    const remark = $('#advertise-remark').val();
    const accessory = $('#advertising-accessory-btn').attr('src');
    const contractName = "广告位租赁合同";
    if (price != '' && leasee != '' && leaseeContacts != '' && leaseeTel != '' && size != '' && locations != '') {
        if ($('#advertise-title-p').prop('class') == 'gai') {
            //编辑
            const _id = $('#advertise-title-p').data('id');
            ajax({
                url: '/advertise',
                type: "PUT",
                data: {
                    _id,
                    communityId,
                    advertiseportId,
                    price,
                    leasee,
                    leaseeContacts,
                    leaseeTel,
                    size,
                    locations,
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory
                },
                success(res) {
                    if (res.code == 200) {
                        alert("修改合同成功");
                        $('#add-advertising-contract-modalbox').hide();
                        showAdvertiseData();
                        clearData();
                    } else {
                        alert("修改合同失败");
                        $('#add-advertising-contract-modalbox').hide();
                        clearData();
                    }
                }
            });
        } else {
            //新增
            ajax({
                url: '/advertise',
                type: "POST",
                data: {
                    communityId,
                    advertiseportId,
                    price,
                    leasee,
                    leaseeContacts,
                    leaseeTel,
                    size,
                    locations,
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory,
                    contractName
                },
                success(res) {
                    if (res.code == 200) {
                        alert("新增合同成功");
                        const objs = {
                            advertiseId: res.data._id,
                            numbers: res.data.advertiseportId.advertisingNumber, //资源名称
                            leaseeContacts: res.data.leaseeContacts,//联系人
                            contractNumber: res.data.contractNumber,//合同编号
                            contractName,
                            price:res.data.price,//收费金额  2
                            leaseeTel:res.data.leaseeTel,//联系电话   2
                            tenant:res.data.tenant, //租户  2
                            signingDate:res.data.signingDate,//签订日期  2
                            off_hire:res.data.off_hire,//停租日期   2
                            start_date:res.data.start_date,//起租日期`  2
                        }
                        addContracts(objs);
                        $('#add-advertising-contract-modalbox').hide();
                        if ($('#advertising-tb tbody tr').length == searchObj.pageSize) {
                            showPageData();
                        }
                        showAdvertiseData();
                        clearData();
                    } else {
                        alert("新增合同失败");
                        $('#add-advertising-contract-modalbox').hide();
                        clearData();
                    }
                }
            });

        }
    } else {
        alert('输入框都不能为空!')
    }
});



//清除模态框数据
function clearData() {
    $('#advertise-size').val('');
    $('#advertise-price').val('');
    $('#advertise-locations').val('');
    $('#advertise-leasee').val('');
    $('#advertise-leaseeContacts').val('');
    $('#advertise-leaseeTel').val('');
    $('#advertise-contractNumber').val('');
    $('#advertise-tenant').val('');
    $('#advertise-signingDate').val('');
    $('#advertise-representative').val('');
    $('#advertise-tenantContacts').val('');
    $('#advertise-contractType').val('');
    $('#advertise-term').val('');
    $('#advertise-off_hire').val('');
    $('#advertise-start_date').val('');
    $('#advertise-area').val('');
    $('#advertise-earnestMoney').val('');
    $('#advertise-agencyfee').val('');
    $('#advertise-isRentMoney').prop('checked', false);
    $('#advertise-totalMoney').val('');
    $('#advertise-increase').val('');
    $('#advertise-earnestExplain').val('');
    $('#advertise-remark').val('');
}



//渲染广告位租赁合同数据
function showAdvertiseData() {
    ajax({
        url: "/advertise",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                searchObj.pages = res.pages;
                searchObj.total = res.total;
                renderAdvertisedata(res.result);
            } 
        }
    })
}

function renderAdvertisedata(data) {
    $('#advertising-tb tbody').html(data.map(item => `<tr>
    <td>${item.advertiseportId.advertisingNumber}</td>
    <td>${item.locations}</td>
    <td>${item.leasee}</td>
    <td>${item.leaseeContacts}</td>
    <td>${item.leaseeTel}</td>
    <td>${item.start_date}</td>
    <td>${item.off_hire}</td>
    <td>${getType(item.start_date, getDate(), item.off_hire) ? '已生效' : "已失效"}</td>
    <td>${item.size}</td>
    <td>${item.advertiseportId.advertisingName}</td>
    <td>${item.communityId.communityName}</td>
    <td>${item.advertiseportId.advertisingLocation}</td>
    <td>${item.advertiseportId.advertisingSize}m²</td>
    <td>￥${item.price}</td>
    <td><span data-id=${item._id} class='advertise-detail-btn' >详情</span><span class='show-advertise-modal' data-id=${item._id}>编辑</span><span data-id=${item._id} class='del-advertise-btn'>删除</span></td>
</tr>`).join(''));
}



//获取当前日期
function getDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = parseInt(date.getMonth()) + 1;
    const day = date.getDate();
    return `${year}-0${month}-${day}`;
}




//判断合同状态
function getType(data1, data2, data3) {
    const date1 = new Date(data1);
    const date2 = new Date(data2);
    const date3 = new Date(data3);
    if (date2 >= date1 && date2 <= date3) {
        return true;
    } else {
        return false;
    }
}



// 渲染页码相关div
function showPageData() {
    ajax({
        url: "/advertise",
        type: 'GET',
        data: {
            searchObj,
            currentPage: searchObj.currentPage,
            pageSize: searchObj.pageSize,
        },
        success(res) {
            if (res.code == 200) {
                renderPageData(Number(res.pages));
            } 
        }
    })
}

function renderPageData(pages) {
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<span>${i}</span>`;
    }
    $('#advertising-bottom-choose-page-div .add-pages-span').html(html);
    $('#advertising-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#advertising-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
}




//点击切换页面
$('#advertising-bottom-choose-page-div .add-pages-span').on('click', 'span', function () {
    $('#advertising-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(this).addClass('active');
    const currentPage = $(this).text();
    searchObj.currentPage = Number(currentPage);
    showAdvertiseData();
});

//点击切换页面显示条数
$('#advertise-pageSize-select').change(function () {
    const pageSize = $('#advertise-pageSize-select').val();
    searchObj.pageSize = Number(pageSize);
    searchObj.currentPage = 1;
    showAdvertiseData();
    showPageData();
});


//跳至X页事件
$('#advertise-go-page').keyup(function (e) {
    if (e.keyCode == 13) {
        const page = $('#advertise-go-page').val();
        if (page != '' && typeof Number(page) == 'number' && !isNaN(Number(page))) {
            if (Number(page) < 1) {
                searchObj.currentPage = 1;
                showAdvertiseData();
                $('#advertising-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#advertising-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else if (Number(page) > searchObj.pages) {
                searchObj.currentPage = searchObj.pages;
                showAdvertiseData();
                $('#advertising-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#advertising-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            } else {
                searchObj.currentPage = Number(page);
                showAdvertiseData();
                $('#advertising-bottom-choose-page-div .add-pages-span span').removeClass('active');
                $(`#advertising-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
            }
        }
    }
});


//上一页，下一页事件
$('#advertise-prev-span').click(function () {
    if (searchObj.currentPage <= 1) {
        searchObj.currentPage = 1;
    } else {
        searchObj.currentPage--;
    }
    showAdvertiseData();
    $('#advertising-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#advertising-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});


$('#advertise-next-span').click(function () {
    if (searchObj.currentPage == searchObj.pages) {
        searchObj.currentPage = searchObj.pages;
    } else {
        searchObj.currentPage++;
    }
    showAdvertiseData();
    $('#advertising-bottom-choose-page-div .add-pages-span span').removeClass('active');
    $(`#advertising-bottom-choose-page-div .add-pages-span span:nth-child(${searchObj.currentPage})`).addClass('active');
});


//点击搜索按钮查询
$('#search-advertising-btn').click(function () {
    const value = $('#search-advertise').val();
    searchObj.value = value;
    searchObj.currentPage = 1;
    showAdvertiseData();
    showPageData();
});





//点击删除按钮，删除对应客户数据
$('#advertising-tb tbody').on('click', '.del-advertise-btn', function () {
    const _id = $(this).data('id');
    delAdvertiseData(_id);
});


//删除客户数据
function delAdvertiseData(_id) {
    ajax({
        url: '/advertise',
        data: { _id },
        type: "DELETE",
        success(res) {
            if (res.code == 200) {
                // 删除成功
                if ((searchObj.total) % (searchObj.pageSize) == 1) {
                    $('#advertising-tb tbody tr').length == 1 ? searchObj.currentPage-- : searchObj.currentPage;
                    showPageData();
                }
                showAdvertiseData();
            } else {
                alert('抱歉,删除失败');
            }
        }
    })
}






//渲染小区
function showCommunityAdvertise() {
    ajax({
        url: '/community',
        type: "GET",
        data: { value: '' },
        success(res) {
            if (res.code == 200) {
                //设置小区选择
                showAdvertiseSeats(res.result[0]._id);
                $('#advertising-choose-plot').html(res.result.map(item => `<option value=${item._id}>${item.communityName}</option>`).join(''));
            }
        }
    })
}


//渲染指定小区
function showCommunityAdvertiseById(_id) {
    ajax({
        url: '/community',
        type: "GET",
        data: { value: '' },
        success(res) {
            if (res.code == 200) {
                $('#advertising-choose-plot').html(res.result.map(item => `<option value=${item._id}>${item.communityName}</option>`).join(''));
                $('#advertising-choose-plot').val(_id);
            }
        }
    })
}


//渲染广告位根据id
function showAdvertiseSeats(_id) {
    ajax({
        url: '/advertising/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                //设置车位选择
                $('#advertiseNumber-select').html(res.result.map(item => `<option value=${item._id}>${item.advertisingNumber}</option>`).join(''));
            }
        }
    })
}



//渲染指定的广告位根据id
function showAdvertiseSeatsByid(_id, ids) {
    ajax({
        url: '/advertising/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                //设置车位选择
                $('#advertiseNumber-select').html(res.result.map(item => `<option value=${item._id}>${item.advertisingNumber}</option>`).join(''));
                $('#advertiseNumber-select').val(ids);
            }
        }
    })
}


//小区下拉框的选择事件
$('#advertising-choose-plot').change(function () {
    const id = $('#advertising-choose-plot').val();
    showAdvertiseSeats(id);
});






//通过id查询对应的广告位详细合同资料
function getAdvertiseDatasById(_id) {
    ajax({
        url: '/advertise/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                showCommunityAdvertiseById(res.result.communityId._id);
                showAdvertiseSeatsByid(res.result.communityId._id, res.result.advertiseportId._id);
                $('#advertise-size').val(res.result.size);
                $('#advertise-price').val(res.result.price);
                $('#advertise-locations').val(res.result.locations);
                $('#advertise-leasee').val(res.result.leasee);
                $('#advertise-leaseeContacts').val(res.result.leaseeContacts);
                $('#advertise-leaseeTel').val(res.result.leaseeTel);
                $('#advertise-contractNumber').val(res.result.contractNumber);
                $('#advertise-tenant').val(res.result.tenant);
                $('#advertise-signingDate').val(res.result.signingDate);
                $('#advertise-representative').val(res.result.representative);
                $('#advertise-tenantContacts').val(res.result.tenantContacts);
                $('#advertise-contractType').val(res.result.contractType);
                $('#advertise-term').val(res.result.term);
                $('#advertise-off_hire').val(res.result.off_hire);
                $('#advertise-start_date').val(res.result.start_date);
                $('#advertise-area').val(res.result.area);
                $('#advertise-earnestMoney').val(res.result.earnestMoney);
                $('#advertise-agencyfee').val(res.result.agencyfee);
                $('#advertise-isRentMoney').prop('checked', res.result.isRentMoney);
                $('#advertise-totalMoney').val(res.result.totalMoney);
                $('#advertise-increase').val(res.result.increase);
                $('#advertise-earnestExplain').val(res.result.earnestExplain);
                $('#advertise-remark').val(res.result.remark);
                $('#advertising-accessory-btn').attr('src', res.result.accessory);
            } 
        }
    })
}




//上传图片
$('#file-input-advertise').change(function (e) {
    const files = e.target.files;
    const fd = new FormData();
    fd.append('file', files[0]);
    $.ajax({
        url: 'http://localhost:3100/advertise/uploadImages',
        type: "POST",
        data: fd,
        contentType: false,
        processData: false,
        cache: false,
        success(res) {
            if (res.code == 200) {
                $('#advertising-accessory-btn').attr('src', 'http://localhost:3100/' + res.data);
            }
        }
    });
});




//点击详情查询合同图片
$('#advertising-tb tbody').on('click', '.advertise-detail-btn', function () {
    const _id = $(this).data('id');
    getAdvertiseById(_id);
});



//通过id查询对应的广告位租赁合同图片数据
function getAdvertiseById(_id) {
    ajax({
        url: '/advertise/' + _id,
        type: "GET",
        success(res) {
            if (res.code == 200) {
                $('#show-img-div').show();
                $('#cancle-img').attr('src', res.result.accessory);
            }
        }
    })
}



//添加数据到合同管理集合
function addContracts(obj){
    ajax({
        url:'/contracts',
        type:'POST',
        data:obj,
        success(res){
         
        }
    });
}
